import React, { Component } from "react";
/* 1. 引入路由依赖 */
import { HashRouter as Router, Link, Route, Switch } from "react-router-dom";
class Index extends Component {
  render() {
    return <h1>首页</h1>;
  }
}
class User extends Component {
  render() {
    /* 2. 接收到 父组件传入的 routes  */
    console.log(this.props.routes);
    return (
      <div>
        <h1>用户</h1>
        <Link to="/user/detail">用户详情</Link>
        <Switch>
          {this.props.routes.map((route, index) => {
            return (
              <Route
                key={route.key}
                path={route.path}
                render={(props) => {
                  return <route.component {...props} routes={route.routes}></route.component>;
                }}
              ></Route>
            );
          })}
        </Switch>
      </div>
    );
  }
}
class UserDetail extends Component {
  render() {
    return <h1>用户详情部分</h1>;
  }
}
let routes = [
  {
    path: "/index",
    key: "index",
    component: Index,
  },
  {
    key: "user",
    path: "/user",
    component: User,
    routes: [
      {
        path: "/user/detail",
        key: "/user/detail",
        component: UserDetail,
      },
    ],
  },
];
class App extends Component {
  render() {
    return (
      <div>
        <div className="my-router">
          <Router>
            <Link to="/index">首页</Link>
            <Link to="/user">用户</Link>
            {/* <Route path="/index" component={Index}></Route>
            <Route path="/user" component={User}></Route> */}
            {routes.map((route, i) => {
              return (
                <Route
                  path={route.path}
                  key={route.key}
                  render={(props) => {
                    // route.component => User Index
                    // <route.component> => <User routes={route.routes}> <Index>
                    /* 1. 传 routes 子路由 给 组件*/
                    return (
                      <route.component
                        {...props}
                        routes={route.routes}
                      ></route.component>
                    );
                  }}
                ></Route>
              );
            })}
          </Router>
        </div>
      </div>
    );
  }
}

export default App;
